package com.haojii.notifier.easytv;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.haojii.notifier.ObservableTask;

public class EasytvParserTaskAppEngine extends ObservableTask {

	private static final Logger log = Logger.getLogger(EasytvParserTaskAppEngine.class.getName());

	private EasytvEntity easytvEntity;
	
	public EasytvParserTaskAppEngine(EasytvEntity easytvEntity) {
		this.easytvEntity = easytvEntity;
	}
	public EasytvEntity getEasytvEntity() {
		return easytvEntity;
	}
	
	private void checkForUpdate() {
		try {
			
			//URI uri = URIUtils.createURI("http", "easytv.echinatv.com.cn/", -1,"/ItemDet.aspx", "IID=" + id, null);
			
			URL url = new URL(easytvEntity.url); 
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
            String line; 
            boolean startSearching = false;
			//StringBuilder sb = new StringBuilder();
			Pattern p = Pattern.compile(
					"href\\s*=\\s*\"(.+?)\"\\s*>(.+?)</\\s*a\\s*>",
					Pattern.UNICODE_CASE);
			Pattern p2 = Pattern
					.compile("(asf|avi|rm|rmvb|mp3|mp4|avi|wma|wmp|wmv|mov+3gp|mpg|mpeg|rar|zip){1}");
            while ((line = reader.readLine()) != null) { 
            	if (line.contains("<div id=\"download-list\">")) {
					startSearching = true;
				}
				if (startSearching) {
					if (line.contains("</div>"))
						startSearching = false;
						Matcher m = p.matcher(line);
						if (m.find() && p2.matcher(line).find()) {
							String value = m.group(1);
							String key = m.group(2);

							//System.out.println("1->" + m.group(1));
							//System.out.println("2->" + m.group(2));
							//easytvEntity.newLinksMap.put(key, value);
							if(!value.startsWith("ftp:")) // just ignore ftp links now
							{
								EasytvItem item = new EasytvItem(key, value);
								if(!easytvEntity.getItems().contains(item))
								{
									if(!easytvEntity.getNewItems().contains(item))
										easytvEntity.getNewItems().add(item);
								}
							}
						}
					//sb.append(line.trim());
					//sb.append("\n");
				}
            } 
            reader.close(); 

			if(easytvEntity.getNewItems().size()>0)
			{
				this.setChanged();
				this.notifyObservers(easytvEntity);
			}

			// 通知完之后更新缓存的items
			easytvEntity.getItems().addAll(easytvEntity.getNewItems());
			easytvEntity.getNewItems().clear();
		}
		catch (Exception e) {
			log.warning(e.getMessage());
		}

	}

	public void doTask() {
		checkForUpdate();
	}
}
